﻿#region

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Core.Common;

#endregion

namespace Core.Utils
{
    /// <summary>
    ///     Class Implement Public Function
    /// </summary>
    /// <CreatedBy>CuongNQ</CreatedBy>
    /// <Created>20/05/2010</Created>
    public class Utility
    {
        #region EnCryptPassword : No Key use MD5

        /// <summary>
        ///     Function EnCryptPassword
        /// </summary>
        /// <param name="strEncrypt">password</param>
        /// <returns>password is encrypted</returns>
        public static string EnCryptPassword(string strEncrypt)
        {
            var toEncryptArray = Encoding.UTF8.GetBytes(strEncrypt);
            var encoder = new UTF8Encoding();
            var md5 = new MD5CryptoServiceProvider();
            var hashedDataBytes = md5.ComputeHash(encoder.GetBytes(strEncrypt));
            md5.Clear();

            var tdesProvider = new TripleDESCryptoServiceProvider
            {
                Key = hashedDataBytes,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };

            var cTransform = tdesProvider.CreateEncryptor();
            var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdesProvider.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        #endregion

        #region Random Password

        public static string RandomPassWord()
        {
            var strBuilder = new StringBuilder();
            var rand = new Random();
            for (var i = 0; i < 6; i++)
            {
                var temp = rand.Next(1, 3);
                char ch;
                switch (temp)
                {
                    case 1:

                        strBuilder.Append(rand.Next(0, 9));
                        break;
                    case 2:
                        ch = Convert.ToChar(rand.Next(65, 90));
                        strBuilder.Append(ch);
                        break;
                    case 3:
                        ch = Convert.ToChar(rand.Next(97, 122));
                        strBuilder.Append(ch);
                        break;
                }
            }
            return strBuilder.ToString();
        }

        #endregion

        #region ConnectionString

        /// <summary>
        ///     Get Connectionstring in App.Config
        /// </summary>
        /// <param name="connectionName"></param>
        /// <returns></returns>
        public static string GetConnectionStringByConnectionName(string connectionName)
        {
            return ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
        }

        /// <summary>
        ///     Function get value of: DataSource, User Id, Password
        /// </summary>
        /// <param name="connectionName"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValueByKeyInConnectionString(string connectionName, string key)
        {
            var connection = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
            if (!string.IsNullOrEmpty(connection))
            {
                var list = connection.Split(';');
                foreach (var s in list)
                {
                    if (s.Contains(key))
                        return s.Replace(key + "=", "");
                }
            }
            return "";
        }

        #endregion

        #region Process Window

        /// <summary>
        ///     Kill Process by name in windown
        /// </summary>
        /// <param name="name"></param>
        public static void FindAndKillProcess(string name)
        {
            foreach (var clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.StartsWith(name))
                {
                    clsProcess.Kill();
                    //break;
                }
            }
        }

        #endregion

        #region Encrypt and Decrypt string

        /// <summary>
        ///     Encrypt String
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EncryptString(string str)
        {
            var b = Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(b);
        }

        /// <summary>
        ///     Decrypt String
        /// </summary>
        /// <param name="stringEncrypt"></param>
        /// <returns></returns>
        public static string DecryptString(string stringEncrypt)
        {
            var b = Convert.FromBase64String(stringEncrypt);
            return Encoding.UTF8.GetString(b);
        }

        #endregion

        #region Read/Write AppSettings in App.Config

        /// <summary>
        ///     Read value of AppSetting in App.Config by Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ReadAppSettings(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        #endregion

        #region SignDigital

        /// <summary>
        ///     Check exit Certificate in KeyStore of Windown
        /// </summary>
        /// <param name="certName"></param>
        /// <returns></returns>
        public static bool CheckCertificateInDesktop(string certName)
        {
            var my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            my.Open(OpenFlags.ReadOnly);
            return
                my.Certificates.Cast<X509Certificate2>()
                    .Any(cert => certName.ToUpper() == cert.SubjectName.Name.ToUpper());
        }

        /// <summary>
        ///     Function Signing Object
        /// </summary>
        /// <param name="myObject"></param>
        /// <param name="certSubject"></param>
        /// <returns></returns>
        public static byte[] Sign(object myObject, string certSubject)
        {
            // Access Personal (MY) certificate store of current user
            var my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            my.Open(OpenFlags.ReadOnly);

            // Find the certificate we'll use to sign            
            var csp = (from X509Certificate2 cert in my.Certificates
                       where cert.Subject.Contains(certSubject)
                       select (RSACryptoServiceProvider)cert.PrivateKey).FirstOrDefault();
            if (csp == null)
            {
                throw new Exception("No valid cert was found");
            }

            // Hash the data
            var sha1 = new SHA1Managed();

            var data = ObjectToByteArray(myObject);

            var hash = sha1.ComputeHash(data);

            // Sign the hash
            return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
        }

        /// <summary>
        ///     Function VerifySigning Object
        /// </summary>
        /// <param name="myObject"></param>
        /// <param name="signature"></param>
        /// <param name="certSubject"></param>
        /// <returns></returns>
        public static bool Verify(object myObject, byte[] signature, string certSubject)
        {
            // Access Personal (MY) certificate store of current user
            var my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            my.Open(OpenFlags.ReadOnly);

            // Find the certificate we'll use to sign            
            var csp = (from X509Certificate2 cert in my.Certificates
                       where cert.Subject.Contains(certSubject)
                       select (RSACryptoServiceProvider)cert.PublicKey.Key).FirstOrDefault();
            if (csp == null)
            {
                throw new Exception("No valid cert was found");
            }

            // Hash the data
            var sha1 = new SHA1Managed();

            //byte[] data = encoding.GetBytes(text);
            var data = ObjectToByteArray(myObject);

            var hash = sha1.ComputeHash(data);

            // Verify the signature with the hash
            return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
        }

        /// <summary>
        ///     Function convert object to byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ObjectToByteArray(Object obj)
        {
            if (obj == null)
                return null;
            var bf = new BinaryFormatter();
            var ms = new MemoryStream();
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }

        #endregion

        #region Licence

        /// <summary>
        ///     Get Machine Name
        /// </summary>
        /// <returns></returns>
        public static string GetMachineName()
        {
            return Environment.MachineName;
        }

        /// <summary>
        ///     Gen 1
        /// </summary>
        /// <param name="tenbv"></param>
        /// <param name="mabv"></param>
        /// <param name="phanhe"></param>
        /// <param name="maytinh"></param>
        /// <returns></returns>
        public static string GenLicenseThongTin1(string tenbv, string mabv, string phanhe, string maytinh)
        {
            var str = "";
            tenbv = tenbv.ToLower();
            mabv = mabv.ToLower();
            phanhe = phanhe.ToLower();
            maytinh = maytinh.ToLower();
            str += tenbv[0];
            str += EnCryptPassword(tenbv);
            str += mabv[mabv.Length - 1];
            str += EnCryptPassword(mabv);
            str += phanhe[phanhe.Length - 1];
            str += EnCryptPassword(phanhe);
            str += maytinh[0];
            str += EnCryptPassword(maytinh);

            return EnCryptPassword(str);
        }

        /// <summary>
        ///     Gen 2
        /// </summary>
        /// <param name="tenbv"></param>
        /// <param name="mabv"></param>
        /// <param name="phanhe"></param>
        /// <param name="maytinh"></param>
        /// <returns></returns>
        public static string GenLicenseThongTin2(string tenbv, string mabv, string phanhe, string maytinh)
        {
            var str = "";
            tenbv = tenbv.ToLower();
            mabv = mabv.ToLower();
            phanhe = phanhe.ToLower();
            maytinh = maytinh.ToLower();
            str += phanhe[phanhe.Length - 1];
            str += EnCryptPassword(phanhe);
            str += maytinh[0];
            str += EnCryptPassword(maytinh);
            str += tenbv[0];
            str += EnCryptPassword(tenbv);
            str += mabv[mabv.Length - 1];
            str += EnCryptPassword(mabv);

            return EnCryptPassword(str);
        }

        #endregion

        #region Remove/Proper String

        /// <summary>
        ///     Remove character from the string including the number and character
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RemoveCharacter(string source)
        {
            var result = "";
            try
            {
                var tmpBuffer = source.ToCharArray();
                for (var i = 0; i < tmpBuffer.Length; i++)
                    if (CheckIsNumber(tmpBuffer[i].ToString()))
                        result = result + source[i];
                return result;
            }
            catch (Exception)
            {
                return result;
            }
        }

        /// <summary>
        ///     Remove Whitespace From String
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RemoveExtraSpace(string source)
        {
            try
            {
                var result = String.Empty;
                if (String.IsNullOrEmpty(source))
                {
                    return result;
                }
                // Create the Regex.
                var r = new Regex(@"\s+");
                // Strip multiple spaces.
                result = r.Replace(source, @" ");
                return result;
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        ///     Proper Word by Xxxxx
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ProperWord(string source)
        {
            var result = String.Empty;
            if (String.IsNullOrEmpty(source))
            {
                return result;
            }
            // Create the Regex.
            var r = new Regex("[^a-zA-Z]");
            if (!r.IsMatch(source))
            {
                var firstCharacter = source.Substring(0, 1).ToUpper();
                var othersCharacter = source.Substring(1).ToLower();
                result = firstCharacter + othersCharacter;
            }
            else
                result = source;
            return result;
        }

        /// <summary>
        ///     Proper string by Xxxx Xxxx Xxxx
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ProperString(string source)
        {
            var result = String.Empty;
            const string space = " ";
            if (String.IsNullOrEmpty(source))
            {
                return result;
            }
            source = RemoveExtraSpace(source);
            var words = source.Split(' ');
            result = words.Aggregate(result, (current, word) => current + (ProperWord(word) + space));
            return result.Trim();
        }

        /// <summary>
        ///     Convert number to string 123 to 000123
        /// </summary>
        /// <param name="number"></param>
        /// <param name="numberStandard"></param>
        /// <returns></returns>
        public static string ConvertNumberToString(int number, int numberStandard)
        {
            var result = number.ToString();
            if (numberStandard >= result.Length)
            {
                var numberZero = numberStandard - result.Length;
                if (numberZero > 0)
                {
                    result = GetStringZero(numberZero) + result;
                }
            }
            return result;
        }

        /// <summary>
        ///     Get string zero
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string GetStringZero(int number)
        {
            var result = String.Empty;
            if (number > 0)
            {
                for (var i = 1; i <= number; i++)
                {
                    result += "0";
                }
            }
            return result;
        }

        /// <summary>
        ///     GetChucNangByPhanHeChucNang
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string GetChucNangByPhanHeChucNang(string source)
        {
            var listPhanHeChucNang = source.Split('#');
            return (from s in listPhanHeChucNang let listChucNangIDs = s.Split(';') where listChucNangIDs.Length > 1 select s).Aggregate(String.Empty, (current, s) => current == "" ? s : current + ";" + s);
        }

        #endregion

        #region DateTime

        /// <summary>
        ///     Return ddmmyyyy
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateTimeToYYYYMMDD(DateTime date)
        {
            var str = "";
            str += date.Year.ToString();
            str += ConvertNumberToString(date.Month, Constant.GenIdLength.DATE);
            str += ConvertNumberToString(date.Day, Constant.GenIdLength.DATE);
            str += ConvertNumberToString(date.Hour, Constant.GenIdLength.DATE);
            str += ConvertNumberToString(date.Minute, Constant.GenIdLength.DATE);
            return str;
        }

        /// <summary>
        ///     Return dd/mm/yyyy
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateTimeToDD_MM_YYYY(DateTime date)
        {
            var str = "";
            str += ConvertNumberToString(date.Day, Constant.GenIdLength.DATE) + "/";
            str += ConvertNumberToString(date.Month, Constant.GenIdLength.DATE) + "/";
            str += date.Year.ToString();
            return str;
        }

        /// <summary>
        ///     Return Ngay thang duoi dang ngay: thang: nam: gio: phut:
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateTimeToText(DateTime date)
        {
            var str = "Ngày: ";
            str += ConvertNumberToString(date.Day, Constant.GenIdLength.DATE) + ", tháng: ";
            str += ConvertNumberToString(date.Month, Constant.GenIdLength.DATE) + " năm: ";
            str += date.Year.ToString();
            str += ", giờ: ";
            str += ConvertNumberToString(date.Hour, Constant.GenIdLength.DATE) + ", phút: ";
            str += ConvertNumberToString(date.Minute, Constant.GenIdLength.DATE);
            return str;
        }

        /// <summary>
        ///     Return Ngay thang duoi dang ngay: thang: nam: gio: phut:
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateTimeToText2(DateTime date)
        {
            var str = "";
            str += ConvertNumberToString(date.Hour, Constant.GenIdLength.DATE) + "h";
            str += ConvertNumberToString(date.Minute, Constant.GenIdLength.DATE);
            str += ", ngày ";
            str += ConvertNumberToString(date.Day, Constant.GenIdLength.DATE) + " tháng ";
            str += ConvertNumberToString(date.Month, Constant.GenIdLength.DATE) + " năm ";
            str += date.Year.ToString();

            return str;
        }

        /// <summary>
        ///     Convert dd/MM/yyyy hh:mm to DateTime
        /// </summary>
        /// <param name="dd_MM_yyyy_hh_mm"></param>
        /// <returns></returns>
        public static DateTime ConvertDD_MM_YYYY_HH_MMToDateTime(string dd_MM_yyyy_hh_mm)
        {
            var listNgayGio = dd_MM_yyyy_hh_mm.Split(' ');
            var listNgay = listNgayGio[0].Split('/');
            var listGio = listNgayGio[1].Split(':');
            var ngay = Convert.ToInt32(listNgay[0]);
            var thang = Convert.ToInt32(listNgay[1]);
            var nam = Convert.ToInt32(listNgay[2]);
            var gio = Convert.ToInt32(listGio[0]);
            var phut = Convert.ToInt32(listGio[1]);
            return CreateDateTime(nam, thang, ngay, gio, phut, 00, 00);
        }

        /// <summary>
        ///     Convert dd/MM/yyyy to DateTime
        /// </summary>
        /// <param name="dd_MM_yyyy"></param>
        /// <returns></returns>
        public static DateTime ConvertDD_MM_YYYYToDateTime(string dd_MM_yyyy)
        {
            var listNgayGio = dd_MM_yyyy.Split(' ');
            var listNgay = listNgayGio[0].Split('/');
            var ngay = Convert.ToInt32(listNgay[0]);
            var thang = Convert.ToInt32(listNgay[1]);
            var nam = Convert.ToInt32(listNgay[2]);
            return CreateDateTimeDD_MM_YYYY(nam, thang, ngay);
        }

        /// <summary>
        ///     Convert dd/MM/yyyy to DateTime + gio phut giay
        /// </summary>
        /// <param name="dd_MM_yyyy"></param>
        /// <param name="gio"></param>
        /// <param name="phut"></param>
        /// <param name="giay"></param>
        /// <returns></returns>
        public static DateTime ConvertDD_MM_YYYYToDateTime(string dd_MM_yyyy, int gio, int phut, int giay)
        {
            var listNgayGio = dd_MM_yyyy.Split(' ');
            var listNgay = listNgayGio[0].Split('/');
            var ngay = Convert.ToInt32(listNgay[0]);
            var thang = Convert.ToInt32(listNgay[1]);
            var nam = Convert.ToInt32(listNgay[2]);
            return CreateDateTime(nam, thang, ngay, gio, phut, giay, 00);
        }

        /// <summary>
        ///     Return dd/mm/yyyy hh:mm
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ConvertDateTimeToDD_MM_YYYY_HH_MM(DateTime date)
        {
            var str = "";
            str += ConvertNumberToString(date.Day, Constant.GenIdLength.DATE) + "/";
            str += ConvertNumberToString(date.Month, Constant.GenIdLength.DATE) + "/";
            str += date.Year.ToString();
            str += " ";
            str += ConvertNumberToString(date.Hour, Constant.GenIdLength.DATE) + ":";
            str += ConvertNumberToString(date.Minute, Constant.GenIdLength.DATE);
            return str;
        }

        /// <summary>
        ///     Function: Create DateTime
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="date"></param>
        /// <param name="hour"></param>
        /// <param name="minute"></param>
        /// <param name="second"></param>
        /// <param name="milisecond"></param>
        /// <returns></returns>
        public static DateTime CreateDateTime(int year, int month, int date, int hour, int minute, int second,
            int milisecond)
        {
            return new DateTime(year, month, date, hour, minute, second, milisecond);
        }

        /// <summary>
        ///     Function: Create DateTime dd/MM/yyyy
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public static DateTime CreateDateTimeDD_MM_YYYY(int year, int month, int date)
        {
            return new DateTime(year, month, date);
        }

        /// <summary>
        ///     Function: Tinh khoang cach theo interval:Day,Mont...
        /// </summary>
        /// <param name="interval"></param>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <returns></returns>
        public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
        {
            var ts = date2 - date1;

            switch (interval)
            {
                case DateInterval.Year:
                    return date2.Year - date1.Year;
                case DateInterval.Month:
                    return (date2.Month - date1.Month) + (12 * (date2.Year - date1.Year));
                case DateInterval.Weekday:
                    return Fix(ts.TotalDays) / 7;
                case DateInterval.Day:
                    return Fix(ts.TotalDays);
                case DateInterval.Hour:
                    return Fix(ts.TotalHours);
                case DateInterval.Minute:
                    return Fix(ts.TotalMinutes);
                default:
                    return Fix(ts.TotalSeconds);
            }
        }

        /// <summary>
        ///     Function: Private of DateDiff
        /// </summary>
        /// <param name="Number"></param>
        /// <returns></returns>
        private static long Fix(double Number)
        {
            if (Number >= 0)
            {
                return (long)Math.Floor(Number);
            }
            return (long)Math.Ceiling(Number);
        }

        #endregion

        #region DataGridView: getSelectedId, checkRowsSelected, gGetRowsIndexSelected, SearchDataOnGridView, deleteRowsSelected

        /// <summary>
        ///     Function: Xoa rows theo listRow da chon
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="listIds"></param>
        /// <returns></returns>
        public static bool DeleteRowsSelected(DataGridView dgvEntities, List<string> listIds)
        {
            try
            {
                //int i = 1;
                //bool delete = false;
                var listRows =
                    dgvEntities.Rows.Cast<DataGridViewRow>()
                        .Where(row => listIds.Any(id => id.ToLower() == row.Cells[0].Value.ToString().ToLower()))
                        .ToList();

                //Delete all rows selected in dgvEntities
                foreach (var row in listRows)
                {
                    dgvEntities.Rows.Remove(row);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///     Function: Xoa rows theo listRow da chon
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteRowsSelected(DataGridView dgvEntities, string id)
        {
            try
            {
                var listRows = new List<DataGridViewRow>();
                foreach (DataGridViewRow row in dgvEntities.Rows)
                {
                    if (id.ToLower() == row.Cells[0].Value.ToString().ToLower())
                    {
                        listRows.Add(row);
                        break;
                    }
                }
                //Delete all rows selected in dgvEntities
                foreach (var row in listRows)
                {
                    dgvEntities.Rows.Remove(row);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///     Function: Xoa 1 row da chon
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteRowSelected(DataGridView dgvEntities, string id)
        {
            try
            {
                var i = 1;
                var delete = false;
                var rowXoa = new DataGridViewRow();

                foreach (DataGridViewRow row in dgvEntities.Rows)
                {
                    if (id.ToLower() == row.Cells[0].Value.ToString().ToLower())
                    {
                        rowXoa = row;
                        delete = true;
                    }
                    //Reset index
                    if (!delete)
                    {
                        row.Cells[1].Value = i;
                        i++;
                    }
                    else
                    {
                        delete = false;
                    }
                }

                //Delete row selected in dgvEntities
                dgvEntities.Rows.Remove(rowXoa);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///     Function: get index by id
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static int GetRowIndexById(DataGridView dgvEntities, string id)
        {
            try
            {
                var rowIndex = -1;
                foreach (DataGridViewRow row in dgvEntities.Rows)
                {
                    if (id.ToLower() == row.Cells[0].Value.ToString().ToLower())
                    {
                        rowIndex = row.Index;
                        break;
                    }
                }
                return rowIndex;
            }
            catch
            {
                return -1;
            }
        }

        public static List<string> GetEntitiesIdSelected(DataGridView dgvEntities)
        {
            var listEntitiesId = new List<string>();
            var idSelected = String.Empty;
            var rowIndexSelected = 0;

            foreach (DataGridViewRow row in dgvEntities.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    var isChecked = (bool)row.Cells[1].Value;
                    if (isChecked)
                    {
                        var enId = row.Cells[0].Value.ToString();
                        listEntitiesId.Add(enId);
                        rowIndexSelected = row.Index;
                    }
                    else if (row.Selected)
                    {
                        idSelected = row.Cells[0].Value.ToString();
                    }
                }
                else if (row.Selected)
                {
                    idSelected = row.Cells[0].Value.ToString();
                }
            }
            if (listEntitiesId.Count == 0 && !String.IsNullOrEmpty(idSelected))
            {
                listEntitiesId.Add(idSelected);
            }
            else if (listEntitiesId.Count == 1 && !String.IsNullOrEmpty(idSelected))
            {
                if (listEntitiesId[0] != idSelected)
                {
                    dgvEntities.Focus();
                    dgvEntities.Rows[rowIndexSelected].Selected = true;
                    dgvEntities.CurrentCell = dgvEntities.Rows[rowIndexSelected].Cells[2];
                }
            }
            return listEntitiesId;
        }

        public static List<DataGridViewRow> GetRowsSelected(DataGridView dgvEntities)
        {
            var listRows = new List<DataGridViewRow>();
            DataGridViewRow rowSelected = null;
            var rowIndexSelected = 0;

            foreach (DataGridViewRow row in dgvEntities.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    var isChecked = (bool)row.Cells[1].Value;
                    if (isChecked)
                    {
                        listRows.Add(row);
                        rowIndexSelected = row.Index;
                    }
                    else if (row.Selected)
                    {
                        rowSelected = row;
                    }
                }
                else if (row.Selected)
                {
                    rowSelected = row;
                }
            }
            if (listRows.Count == 0 && rowSelected != null)
            {
                listRows.Add(rowSelected);
            }
            else if (listRows.Count == 1 && rowSelected != null)
            {
                if (listRows[0] != rowSelected)
                {
                    dgvEntities.Focus();
                    dgvEntities.Rows[rowIndexSelected].Selected = true;
                    dgvEntities.CurrentCell = dgvEntities.Rows[rowIndexSelected].Cells[2];
                }
            }
            return listRows;
        }

        public static int CheckRowsSelected(DataGridView dgvEntities)
        {
            var result = -1;
            foreach (DataGridViewRow row in dgvEntities.Rows)
            {
                if (row.Selected)
                {
                    result = row.Index;
                    break;
                }
            }
            return result;
        }

        public static List<string> GetRowsIndexSelected(DataGridView dgvEntities)
        {
            //var listRowsIndexs = new List<string>();
            //string enIndex = String.Empty;
            //foreach (DataGridViewRow row in dgvEntities.Rows)
            //{
            //    if (row.Cells[1].Value != null)
            //    {
            //        var isChecked = (bool)row.Cells[1].Value;
            //        if (isChecked)
            //        {
            //            enIndex = row.Index.ToString();
            //            listRowsIndexs.Add(enIndex);
            //        }
            //    }
            //}
            //return listRowsIndexs;
            var listRowsIndexs = new List<string>();
            var idSelected = String.Empty;
            var rowIndexSelected = 0;

            foreach (DataGridViewRow row in dgvEntities.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    var isChecked = (bool)row.Cells[1].Value;
                    if (isChecked)
                    {
                        var enIndex = row.Index.ToString();
                        listRowsIndexs.Add(enIndex);
                        rowIndexSelected = row.Index;
                    }
                    else if (row.Selected)
                    {
                        idSelected = row.Index.ToString();
                    }
                }
            }
            if (listRowsIndexs.Count == 0 && !String.IsNullOrEmpty(idSelected))
            {
                listRowsIndexs.Add(idSelected);
            }
            else if (listRowsIndexs.Count == 1 && !String.IsNullOrEmpty(idSelected))
            {
                if (listRowsIndexs[0] != idSelected)
                {
                    dgvEntities.Focus();
                    dgvEntities.Rows[rowIndexSelected].Selected = true;
                    dgvEntities.CurrentCell = dgvEntities.Rows[rowIndexSelected].Cells[2];
                }
            }
            return listRowsIndexs;
        }

        /// <summary>
        ///     Function check or unchecked checkboxheader colum in DataGridView
        ///     <param name="dgView"></param>
        /// </summary>
        public static void CheckOrUnCheckCheckBoxHeaderInDataGridView(DataGridView dgView)
        {
            ((CheckBox)dgView.Controls.Find("checkboxHeader", true)[0]).Checked =
                !((CheckBox)dgView.Controls.Find("checkboxHeader", true)[0]).Checked;
        }

        /// <summary>
        ///     Function uncheck checkboxheader colum in DataGridView
        ///     <param name="dgView"></param>
        /// </summary>
        public static void UnCheckCheckBoxHeaderInDataGridView(DataGridView dgView)
        {
            if (dgView != null)
            {
                if (((CheckBox)dgView.Controls.Find("checkboxHeader", true)[0]).Checked)
                {
                    ((CheckBox)dgView.Controls.Find("checkboxHeader", true)[0]).Checked = false;
                }
            }
        }

        /// <summary>
        ///     Function check all items in DataGridView
        ///     <param name="dgView"></param>
        /// </summary>
        public static void CheckAllItemInDataGridView(DataGridView dgView)
        {
            //CuongNQ modified: Check null
            //Edited: 19/06/2010
            if (dgView != null && dgView.RowCount > 0)
            {
                for (var i = 0; i < dgView.RowCount; i++)
                {
                    dgView[1, i].Value = ((CheckBox)dgView.Controls.Find("checkboxHeader", true)[0]).Checked;
                }
                dgView.Focus();
                dgView.CurrentCell = dgView[2, 0];
                dgView.Rows[0].Selected = true;
            }
        }

        /// <summary>
        ///     Function reload STT items in DataGridView
        ///     <param name="dgView"></param>
        /// </summary>
        public static void ReloadSttInDataGridView(DataGridView dgView)
        {
            if (dgView != null && dgView.RowCount > 0)
            {
                for (var i = 0; i < dgView.RowCount; i++)
                {
                    dgView[2, i].Value = i + 1;
                }
            }
        }

        /// <summary>
        ///     Function reload STT items in DataGridView
        ///     <param name="dgView"></param>
        /// </summary>
        public static void ReloadSttInDataGridView2(DataGridView dgView)
        {
            if (dgView != null && dgView.RowCount > 0)
            {
                for (var i = 0; i < dgView.RowCount; i++)
                {
                    dgView[1, i].Value = i + 1;
                }
            }
        }

        #region Tim kiem du lieu tren datagridview

        /// <summary>
        ///     Danh sach cac ki tu tieng viet can loc
        /// </summary>
        private static readonly string[] VietNamChar =
        {
            "aAeEoOuUiIdDyY",
            "áàạảãâấầậẩẫăắằặẳẵ",
            "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
            "éèẹẻẽêếềệểễ",
            "ÉÈẸẺẼÊẾỀỆỂỄ",
            "óòọỏõôốồộổỗơớờợởỡ",
            "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
            "úùụủũưứừựửữ",
            "ÚÙỤỦŨƯỨỪỰỬỮ",
            "íìịỉĩ",
            "ÍÌỊỈĨ",
            "đ",
            "Đ",
            "ýỳỵỷỹ",
            "ÝỲỴỶỸ"
        };

        /// <summary>
        ///     Function: Tim kiem trong DataGridView load het gia tri ra gird
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="timkiem"></param>
        public static void SearchDataOnGridView(DataGridView dgvEntities, string timkiem)
        {
            var i = 0;
            foreach (DataGridViewRow row in dgvEntities.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    row.Visible = true;
                    var check = false;
                    foreach (var cell in row.Cells)
                    {
                        try
                        {
                            if (((DataGridViewCell)cell).Value.ToString().ToLower().Contains(timkiem.ToLower()))
                            {
                                check = true;
                                break;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    if (check)
                    {
                        i += 1;
                        row.Cells[2].Value = i;
                    }
                    else
                    {
                        row.Visible = false;
                    }
                }
            }
        }

        /// <summary>
        ///     Tuantm
        ///     Function: Tim kiem trong DataGridView load het gia tri ra gird trong truong hop gird khong co truong STT
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="timkiem"></param>
        public static void SearchDataOnGridViewWithoutIndex(DataGridView dgvEntities, string timkiem)
        {
            foreach (DataGridViewRow row in dgvEntities.Rows)
            {
                foreach (var cell in row.Cells)
                {
                    if (((DataGridViewCell)cell).Value != null)
                    {
                        try
                        {
                            if (((DataGridViewCell)cell).Value.ToString().ToLower().Contains(timkiem.ToLower()))
                            {
                                row.Visible = true;
                                break;
                            }
                            row.Visible = false;
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
        }

        /// <summary>
        ///     Function: Tim kiem trong DataGridView theo thu tu tu tren xuong && quay nguoc lai
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="timkiem"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static int SearchDataOnGridView(DataGridView dgvEntities, string timkiem, int index)
        {
            if (index >= dgvEntities.Rows.Count)
                return dgvEntities.Rows.Count + 1;
            for (var j = index; j < dgvEntities.Rows.Count; j++)
            {
                var check = false;
                foreach (var cell in dgvEntities.Rows[j].Cells)
                {
                    try
                    {
                        if (((DataGridViewCell)cell).Value.ToString().ToLower().Contains(timkiem.ToLower()))
                        {
                            check = true;
                            break;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                if (check)
                {
                    dgvEntities.Rows[j].Selected = true;
                    dgvEntities.FirstDisplayedScrollingRowIndex = j;
                    return j + 1;
                }
            }

            return dgvEntities.Rows.Count + 1;
        }

        /// <summary>
        ///     Function: Tim kiem trong DataGridView theo thu tu tu tren xuong && quay nguoc lai
        /// </summary>
        /// <param name="dgvEntities"></param>
        /// <param name="timkiem"></param>
        /// <param name="index"></param>
        /// <param name="listCell"></param>
        /// <returns></returns>
        public static int SearchDataOnGridView(DataGridView dgvEntities, string timkiem, int index, List<int> listCell)
        {
            if (index >= dgvEntities.Rows.Count)
                return dgvEntities.Rows.Count + 1;
            for (var j = index; j < dgvEntities.Rows.Count; j++)
            {
                var check = false;
                foreach (var cellIndex in listCell)
                {
                    try
                    {
                        var giatri = (dgvEntities.Rows[j].Cells[cellIndex]).Value.ToString().ToLower();
                        if (FilterTiengViet(giatri).Contains(FilterTiengViet(timkiem).ToLower()))
                        {
                            check = true;
                            break;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                if (check)
                {
                    dgvEntities.Rows[j].Selected = true;
                    dgvEntities.FirstDisplayedScrollingRowIndex = j;
                    return j + 1;
                }
            }

            return dgvEntities.Rows.Count + 1;
        }

        /// <summary>
        ///     Ham loc & thay the ki tu tieng viet = ki tu unicode tuong ung
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FilterTiengViet(string str)
        {
            //Thay thế và lọc dấu từng char     
            for (var i = 1; i < VietNamChar.Length; i++)
            {
                for (var j = 0; j < VietNamChar[i].Length; j++)
                    str = str.Replace(VietNamChar[i][j], VietNamChar[0][i - 1]);
            }
            return RemoveExtraSpace(str);
        }

        #endregion

        #endregion

        #region TreeView: CheckOrUncheck

        /// <summary>
        ///     Function: Check all hoac bo check all tren treeview
        /// </summary>
        /// <param name="treeView"></param>
        public static void CheckOrUncheckTreeView(TreeView treeView)
        {
            if (treeView.Nodes.Count > 0)
            {
                var check = treeView.Nodes[0].Checked;
                foreach (TreeNode node in treeView.Nodes)
                {
                    node.Checked = !check;
                }
            }
        }

        #endregion

        #region Read Excel File

        /// <summary>
        ///     Function Import File Excel
        /// </summary>
        /// <param name="fileName">Name of file Excel</param>
        /// <param name="hasHeaders">true or false</param>
        /// <returns>DataSet</returns>
        public static DataSet ImportExcelXls(string fileName, bool hasHeaders)
        {
            var hdr = hasHeaders ? "Yes" : "No";
            var strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                             fileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=" +
                             hdr + ";IMEX=1\"";

            var output = new DataSet();

            using (var conn = new OleDbConnection(strConn))
            {
                conn.Open();

                var schemaTable = conn.GetOleDbSchemaTable(
                    OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                foreach (DataRow schemaRow in schemaTable.Rows)
                {
                    var sheet = schemaRow["TABLE_NAME"].ToString();

                    var cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
                    cmd.CommandType = CommandType.Text;

                    var outputTable = new DataTable(sheet);
                    output.Tables.Add(outputTable);
                    new OleDbDataAdapter(cmd).Fill(outputTable);
                }
                conn.Close();
            }
            return output;
        }

        /// <summary>
        ///     Function Get DataTable
        /// </summary>
        /// <param name="dataSet">DataSet</param>
        /// <param name="name">Name of sheet</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableByName(DataSet dataSet, string name)
        {
            if (dataSet != null && dataSet.Tables.Count > 0)
                return dataSet.Tables.Cast<DataTable>()
                    .FirstOrDefault(table => table != null && table.TableName == name);
            return null;
        }

        #endregion

        #region Export to excel

        #endregion

        #region TrangThaiToInt, StringToTrangThai, LoaiBangGiaToInt, StringToLoaiBangGia, KieuXuatNhapFromInt, StringToKieuXuatNhap

        public static string TrangThaiFromInt(string i)
        {
            switch (i)
            {
                case Constant.TrangThai.HoatDong:
                    {
                        return Constant.TrangThai.HoatDongView;
                    }
                case Constant.TrangThai.KhongHoatDong:
                    {
                        return Constant.TrangThai.KhongHoatDongView;
                    }
                //case Constant.TrangThai.DaXoa:
                //	{
                //		return Constant.TrangThai.DaXoaView;
                //	}
                //case Constant.TrangThai.TamDung:
                //	{
                //		return Constant.TrangThai.TamDungView;
                //	}
                default:
                    return "";
            }
        }

        public static string StringToTrangThai(string i)
        {
            switch (i)
            {
                case Constant.TrangThai.HoatDongView:
                    {
                        return Constant.TrangThai.HoatDong;
                    }
                case Constant.TrangThai.KhongHoatDongView:
                    {
                        return Constant.TrangThai.KhongHoatDong;
                    }
                //case Constant.TrangThai.DaXoaView:
                //	{
                //		return Constant.TrangThai.DaXoa;
                //	}
                default:
                    return "0";
            }
        }

        public static string TrangThaiBienLaiFormInt(int i)
        {
            switch (i)
            {
                case Constant.TrangThaiBienLai.TaoMoi:
                    {
                        return Constant.TrangThaiBienLai.TaoMoiView;
                    }
                case Constant.TrangThaiBienLai.DaThanhToan:
                    {
                        return Constant.TrangThaiBienLai.DaThanhToanView;
                    }
                case Constant.TrangThaiBienLai.DaHuy:
                    {
                        return Constant.TrangThaiBienLai.DaHuyView;
                    }
                /*case Constant.TrangThaiBienLai.DaXoa:
        {
            return Constant.TrangThaiBienLai.DaXoaView;
        }*/
                case Constant.TrangThaiBienLai.ChuaThanhToan:
                    {
                        return Constant.TrangThaiBienLai.ChuaThanhToanView;
                    }
                case Constant.TrangThaiBienLai.DaChuyen:
                    {
                        return Constant.TrangThaiBienLai.DaChuyenView;
                    }
                default:
                    return "";
            }
        }

        public static int StringToTrangThaiBienLai(string i)
        {
            switch (i)
            {
                case Constant.TrangThaiBienLai.TaoMoiView:
                    {
                        return Constant.TrangThaiBienLai.TaoMoi;
                    }
                case Constant.TrangThaiBienLai.DaThanhToanView:
                    {
                        return Constant.TrangThaiBienLai.DaThanhToan;
                    }
                case Constant.TrangThaiBienLai.DaHuyView:
                    {
                        return Constant.TrangThaiBienLai.DaHuy;
                    }
                /*case Constant.TrangThaiBienLai.DaXoaView:
        {
            return Constant.TrangThaiBienLai.DaXoa;
        }*/
                case Constant.TrangThaiBienLai.ChuaThanhToanView:
                    {
                        return Constant.TrangThaiBienLai.ChuaThanhToan;
                    }
                case Constant.TrangThaiBienLai.DaChuyenView:
                    {
                        return Constant.TrangThaiBienLai.DaChuyen;
                    }
                default:
                    return 0;
            }
        }

        public static string TrangThaiHangFormInt(int i)
        {
            switch (i)
            {
                case 1:
                    {
                        return Constant.TrangThaiMatHang.ConView;
                    }
                case 2:
                    {
                        return Constant.TrangThaiMatHang.HetView;
                    }
                default:
                    return "";
            }
        }

        public static string KieuThanhToanFormInt(int i)
        {
            switch (i)
            {
                case Constant.HinhThucThanhToan.TienMat:
                    {
                        return Constant.HinhThucThanhToan.TienMatView;
                    }
                case Constant.HinhThucThanhToan.NganHang:
                    {
                        return Constant.HinhThucThanhToan.NganHangView;
                    }
                case Constant.HinhThucThanhToan.ThanhToanSau:
                    {
                        return Constant.HinhThucThanhToan.ThanhToanSauView;
                    }
                case Constant.HinhThucThanhToan.ChiPhi:
                    {
                        return Constant.HinhThucThanhToan.ChiPhiView;
                    }
                default:
                    return "";
            }
        }

        public static string KieuXuatNhapFromInt(int i)
        {
            switch (i)
            {
                case 1:
                    {
                        return "Xuất sử dụng";
                    }
                case 2:
                    {
                        return "Xuất tiêu hao";
                    }
                case 3:
                    {
                        return "Xuất trả";
                    }
                case 4:
                    {
                        return "Xuất chuyển";
                    }
                default:
                    return "";
            }
        }

        public static int StringToKieuXuatNhap(string i)
        {
            switch (i)
            {
                case "Xuất sử dụng":
                    {
                        return 1;
                    }
                case "Xuất tiêu hao":
                    {
                        return 2;
                    }
                case "Xuất trả":
                    {
                        return 3;
                    }
                case "Xuất chuyển":
                    {
                        return 4;
                    }
                default:
                    return 0;
            }
        }

        public static string KieuKhachHangFromInt(int i)
        {
            switch (i)
            {
                case 1:
                    {
                        return "Nhà cung cấp";
                    }
                case 2:
                    {
                        return "Tiêu thụ";
                    }
                default:
                    return "";
            }
        }

        public static int StringToKieuKhachHang(string i)
        {
            switch (i)
            {
                case "Nhà cung cấp":
                    {
                        return 1;
                    }
                case "Tiêu thụ":
                    {
                        return 2;
                    }
                default:
                    return 0;
            }
        }

        public static string KieuNhapXuatCTFromInt(int i)
        {
            switch (i)
            {
                case 1:
                    {
                        return "Mua hàng";
                    }
                case 2:
                    {
                        return "Nhập khẩu hàng";
                    }
                case 3:
                    {
                        return "Xuất trả hàng";
                    }
                default:
                    return "";
            }
        }

        public static int StringToKieuNhapXuatCT(string i)
        {
            switch (i)
            {
                case "Mua hàng":
                    {
                        return 1;
                    }
                case "Nhập khẩu hàng":
                    {
                        return 2;
                    }
                case "Xuất trả hàng":
                    {
                        return 3;
                    }
                default:
                    return 0;
            }
        }

        public static string KieuNhapXuatKhoFromInt(int i)
        {
            switch (i)
            {
                case 1:
                    {
                        return "Nhập kho";
                    }
                case 2:
                    {
                        return "Nhập lại kho";
                    }
                case 3:
                    {
                        return "Xuất chuyển kho";
                    }
                case 4:
                    {
                        return "Xuất sử dụng";
                    }
                case 5:
                    {
                        return "Xuất trả";
                    }
                case 6:
                    {
                        return "Xuất tiêu hao";
                    }
                case 7:
                    {
                        return "Xuất khác";
                    }
                case 8:
                    {
                        return "Xuất bán lẻ";
                    }
                default:
                    return "";
            }
        }

        public static int StringToKieuNhapXuatKho(string i)
        {
            switch (i)
            {
                case "Nhập kho":
                    {
                        return 1;
                    }
                case "Nhập lại kho":
                    {
                        return 2;
                    }
                case "Xuất chuyển kho":
                    {
                        return 3;
                    }
                case "Xuất sử dụng":
                    {
                        return 4;
                    }
                case "Xuất trả":
                    {
                        return 5;
                    }
                case "Xuất tiêu hao":
                    {
                        return 6;
                    }
                case "Xuất khác":
                    {
                        return 7;
                    }
                case "Xuất bán lẻ":
                    {
                        return 8;
                    }
                default:
                    return 0;
            }
        }

        public static string PPQLDuocFromInt(int i)
        {
            switch (i)
            {
                case 1:
                    {
                        return "Bình quân";
                    }
                case 2:
                    {
                        return "Đích danh";
                    }
                case 3:
                    {
                        return "FIFO";
                    }
                case 4:
                    {
                        return "LIFO";
                    }
                case 5:
                    {
                        return "FEFO";
                    }
                default:
                    return "";
            }
        }

        public static int StringToPPQLDuoc(string i)
        {
            switch (i)
            {
                case "Bình quân":
                    {
                        return 1;
                    }
                case "Đích danh":
                    {
                        return 2;
                    }
                case "FIFO":
                    {
                        return 3;
                    }
                case "LIFO":
                    {
                        return 4;
                    }
                case "FEFO":
                    {
                        return 5;
                    }
                default:
                    return 0;
            }
        }

        public static string KieuViTriFromInt(int i)
        {
            switch (i)
            {
                case Constant.KieuViTri.ViTriBanHang:
                    {
                        return Constant.KieuViTri.ViTriBanHangView;
                    }
                case Constant.KieuViTri.ViTriThucHien:
                    {
                        return Constant.KieuViTri.ViTriThucHienView;
                    }
                case Constant.KieuViTri.ViTriLuuTru:
                    {
                        return Constant.KieuViTri.ViTriLuuTruView;
                    }
                default:
                    return "";
            }
        }

        public static int StringToKieuViTri(string i)
        {
            switch (i)
            {
                case Constant.KieuViTri.ViTriBanHangView:
                    {
                        return Constant.KieuViTri.ViTriBanHang;
                    }
                case Constant.KieuViTri.ViTriThucHienView:
                    {
                        return Constant.KieuViTri.ViTriThucHien;
                    }
                case Constant.KieuViTri.ViTriLuuTruView:
                    {
                        return Constant.KieuViTri.ViTriLuuTru;
                    }
                default:
                    return 0;
            }
        }

        #endregion

        #region DateTime To Id

        public static string DateTimeToId(DateTime time)
        {
            var str = "";

            str += time.Day.ToString();
            str += time.Month.ToString();
            str += time.Year.ToString();
            str += time.Hour.ToString();
            str += time.Minute.ToString();
            str += time.Second.ToString();
            str += time.Millisecond.ToString();

            return str;
        }

        #endregion

        #region CheckIsNumber

        public static bool CheckIsNumber(string str)
        {
            try
            {
                if (str.IndexOf('-') >= 0) return false;
                var num = Convert.ToInt32(str);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool CheckIsNumberDecimal(string str)
        {
            try
            {
                if (str.IndexOf('-') >= 0) return false;
                var num = Convert.ToDecimal(str);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static void ValidateNumberControl(TextBox textboxControl, string defaulttext)
        {
            var r = new Regex("[^0-9]");
            var tmpValue = textboxControl.Text;
            if (!String.IsNullOrEmpty(tmpValue))
            {
                if (r.IsMatch(tmpValue))
                {
                    var th = RemoveCharacter(tmpValue);
                    if (th == "" || th == "0")
                    {
                        th = defaulttext;
                    }
                    var tienthue = Convert.ToDecimal(th);
                    var cursorPosition = textboxControl.SelectionStart;
                    //textboxControl.SelectionStart = tmptienthue.Length;                    
                    textboxControl.Text = tienthue.ToString();
                    textboxControl.SelectionStart = cursorPosition == 0 ? 0 : cursorPosition - 1;
                }
                else if (tmpValue.Trim() == "0" && defaulttext != "0")
                {
                    var cursorPosition = textboxControl.SelectionStart;
                    textboxControl.Text = "1";
                    textboxControl.SelectionStart = cursorPosition == 0 ? 0 : cursorPosition - 1;
                }
            }
            //else
            //{
            //    textboxControl.Text = defaulttext;
            //}
        }

        public static double Roundnum(double num, int place)
        {
            var n = num * Math.Pow(10, place);
            n = Math.Sign(n) * Math.Abs(Math.Floor(n + .5));
            return n / Math.Pow(10, place);
        }

        #endregion

        #region Validate email

        public const string MatchEmailPattern =
            @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
            + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				        [0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
            + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				        [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
            + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

        public static bool IsEmail(string email)
        {
            if (email != null) return Regex.IsMatch(email, MatchEmailPattern);
            return false;
        }

        #endregion

        #region CheckBoxList

        /// <summary>
        ///     Set gia tri da selected
        /// </summary>
        /// <param name="cblControl"></param>
        /// <param name="value"></param>
        public static void SetListCheckedToControl(CheckedListBox cblControl, string value)
        {
            if (!string.IsNullOrEmpty(value) && cblControl.Items.Count > 0)
            {
                var listvalue = value.Split(';');
                foreach (var s in listvalue)
                {
                    for (var i = 0; i < cblControl.Items.Count; i++)
                    {
                        if (cblControl.Items[i].ToString().ToLower() == s.ToLower())
                        {
                            cblControl.SetItemChecked(i, true);
                            break;
                        }
                    }
                }
            }
        }

        /// <summary>
        ///     Lay ra danh sach da selected
        /// </summary>
        /// <param name="cblControl"></param>
        /// <returns></returns>
        public static string GetListCheckedToControl(CheckedListBox cblControl)
        {
            var s = "";
            if (cblControl.CheckedItems.Count > 0)
                s = cblControl.CheckedItems.Cast<object>().Aggregate(s, (current, o) => current + o + ";");
            return s.Trim(';');
        }

        #endregion

        #region Ham doc so tien thanh chu so

        private static readonly string[] ChuSo = new string[10]
        {
            " không", " một", " hai", " ba", " bốn", " năm", " sáu", " bẩy",
            " tám", " chín"
        };

        private static readonly string[] Tien = new string[6] { "", " nghìn", " triệu", " tỷ", " nghìn tỷ", " triệu tỷ" };

        /// <summary>
        ///     Ham doc so tien thanh chu so
        /// </summary>
        /// <param name="soTien"></param>
        /// <param name="strTail"></param>
        /// <returns></returns>
        public static string DocTienBangChu(long soTien, string strTail)
        {
            int lan, i;
            long so;
            var ketQua = "";
            var viTri = new int[6];
            if (soTien < 0)
                ketQua = "(âm) ";
            if (soTien == 0) return "Không đồng !";
            if (soTien > 0)
                so = soTien;
            else
                so = -soTien;
            //Kiểm tra số quá lớn
            if (soTien > 8999999999999999)
                return "";
            viTri[5] = (int)(so / 1000000000000000);
            so = so - long.Parse(viTri[5].ToString()) * 1000000000000000;
            viTri[4] = (int)(so / 1000000000000);
            so = so - long.Parse(viTri[4].ToString()) * +1000000000000;
            viTri[3] = (int)(so / 1000000000);
            so = so - long.Parse(viTri[3].ToString()) * 1000000000;
            viTri[2] = (int)(so / 1000000);
            viTri[1] = (int)((so % 1000000) / 1000);
            viTri[0] = (int)(so % 1000);
            if (viTri[5] > 0)
                lan = 5;
            else if (viTri[4] > 0)
                lan = 4;
            else if (viTri[3] > 0)
                lan = 3;
            else if (viTri[2] > 0)
                lan = 2;
            else if (viTri[1] > 0)
                lan = 1;
            else
                lan = 0;
            for (i = lan; i >= 0; i--)
            {
                var tmp = DocSo3ChuSo(viTri[i]);
                ketQua += tmp;
                if (viTri[i] != 0) ketQua += Tien[i];
                if ((i > 0) && (!string.IsNullOrEmpty(tmp))) ketQua += ","; //&& (!string.IsNullOrEmpty(tmp))
            }
            if (ketQua.Substring(ketQua.Length - 1, 1) == ",") ketQua = ketQua.Substring(0, ketQua.Length - 1);
            ketQua = ketQua.Trim() + strTail;
            return ketQua.Substring(0, 1).ToUpper() + ketQua.Substring(1);
        }

        /// <summary>
        ///     Ham doc 3 chu so
        /// </summary>
        /// <param name="baso"></param>
        /// <returns></returns>
        private static string DocSo3ChuSo(int baso)
        {
            var ketQua = "";
            var tram = (baso / 100);
            var chuc = ((baso % 100) / 10);
            var donvi = baso % 10;
            if ((tram == 0) && (chuc == 0) && (donvi == 0)) return "";
            if (tram != 0)
            {
                ketQua += ChuSo[tram] + " trăm";
                if ((chuc == 0) && (donvi != 0)) ketQua += " linh";
            }
            if ((chuc != 0) && (chuc != 1))
            {
                ketQua += ChuSo[chuc] + " mươi";
                if ((chuc == 0) && (donvi != 0)) ketQua = ketQua + " linh";
            }
            if (chuc == 1) ketQua += " mười";
            switch (donvi)
            {
                case 1:
                    if ((chuc != 0) && (chuc != 1))
                    {
                        ketQua += " mốt";
                    }
                    else
                    {
                        ketQua += ChuSo[donvi];
                    }
                    break;
                case 5:
                    if (chuc == 0)
                    {
                        ketQua += ChuSo[donvi];
                    }
                    else
                    {
                        ketQua += " lăm";
                    }
                    break;
                default:
                    if (donvi != 0)
                    {
                        ketQua += ChuSo[donvi];
                    }
                    break;
            }
            return ketQua;
        }

        /// <summary>
        ///     Function chuyen so tien 20000000 thanh 20.000.000 Đ
        /// </summary>
        /// <param name="sotien"></param>
        /// <returns></returns>
        public static string ChuyenTienThanhKieuTien(Int32 sotien)
        {
            if (sotien == 0)
                return "0";
            return String.Format("{0:0,0}", sotien).Replace(',', '.');
        }

        #endregion

        #region function to build the contains expression

        /// <summary>
        ///     Build container Expression for LINQ
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="valueSelector"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
            Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
        {
            if (null == valueSelector)
            {
                throw new ArgumentNullException("valueSelector");
            }
            if (null == values)
            {
                throw new ArgumentNullException("values");
            }
            var parameter = valueSelector.Parameters.Single();
            if (!values.Any())
            {
                return e => false;
            }
            var equals =
                values.Select(
                    value =>
                        (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
            var body = equals.Aggregate(Expression.Or);
            return Expression.Lambda<Func<TElement, bool>>(body, parameter);
        }

        #endregion

        #region Ham chuyen doi dinh dang so

        /// <summary>
        ///     Huybt 15/07/2012 : Ham chuyen so sang string theo dinh dang ###,###
        /// </summary>
        /// <param name="iNumber"></param>
        /// <returns></returns>
        public static string ConvertNumberToString(decimal iNumber)
        {
            var myNumber = iNumber.ToString();
            var myResult = "";
            for (var i = myNumber.Length - 1; i >= 0; i--)
            {
                myResult = myNumber[i] + myResult;
                if ((myNumber.Length - i) % 3 == 0 & i > 0)
                    myResult = "," + myResult;
            }

            return myResult;
        }

        /// <summary>
        ///     Huybt 15/07/2012: Ham chuyen chuoi string dinh dang ###,### ve dinh dang ######
        /// </summary>
        /// <param name="sNumber"></param>
        /// <returns></returns>
        public static string ConvertStringToNumber(string sNumber)
        {
            var strNumber = sNumber.Split(Convert.ToChar(","));
            return strNumber.Aggregate("", (current, t) => current + t);
        }

        #endregion

        #region Hàm add item cho cbb Kieu vi tri

        public static void AddItemForCbbKieuViTri(ComboBox cbbKieuViTri)
        {
            var datatable = new DataTable();
            datatable.Columns.Add("Value");
            datatable.Columns.Add("View");

            var row = datatable.NewRow();
            row[0] = Constant.KieuViTri.ViTriBanHang;
            row[1] = Constant.KieuViTri.ViTriBanHangView;
            datatable.Rows.Add(row);

            var row1 = datatable.NewRow();
            row1[0] = Constant.KieuViTri.ViTriThucHien;
            row1[1] = Constant.KieuViTri.ViTriThucHienView;
            datatable.Rows.Add(row1);

            var row2 = datatable.NewRow();
            row2[0] = Constant.KieuViTri.ViTriLuuTru;
            row2[1] = Constant.KieuViTri.ViTriLuuTruView;
            datatable.Rows.Add(row2);

            cbbKieuViTri.DataSource = datatable;
            cbbKieuViTri.DisplayMember = "View";
            cbbKieuViTri.ValueMember = "Value";
        }

        #endregion

        #region Hàm add item cho cbb trạng thái

        public static void AddItemForCbb(ComboBox cbbTrangThai)
        {
            var datatable = new DataTable();
            datatable.Columns.Add("Value");
            datatable.Columns.Add("View");

            var row = datatable.NewRow();
            row[0] = Constant.TrangThai.HoatDong;
            row[1] = Constant.TrangThai.HoatDongView;
            datatable.Rows.Add(row);

            var row1 = datatable.NewRow();
            row1[0] = Constant.TrangThai.KhongHoatDong;
            row1[1] = Constant.TrangThai.KhongHoatDongView;
            datatable.Rows.Add(row1);

            cbbTrangThai.DataSource = datatable;
            cbbTrangThai.DisplayMember = "View";
            cbbTrangThai.ValueMember = "Value";
        }

        #endregion

        #region Hàm add item cho cbb Don Vi Tinh thoi gian

        public static void AddItemForCbbDVT(ComboBox cbbDVT)
        {
            var datatable = new DataTable();
            datatable.Columns.Add("Value");
            datatable.Columns.Add("View");

            var row = datatable.NewRow();
            row[0] = Constant.DonViTinhTG.MaDVTGio;
            row[1] = Constant.DonViTinhTG.TenDVTGio;
            datatable.Rows.Add(row);

            var row1 = datatable.NewRow();
            row1[0] = Constant.DonViTinhTG.MaDVTPhut;
            row1[1] = Constant.DonViTinhTG.TenDVTPhut;
            datatable.Rows.Add(row1);

            var row2 = datatable.NewRow();
            row2[0] = Constant.DonViTinhTG.MaDVTGiay;
            row2[1] = Constant.DonViTinhTG.TenDVTGiay;
            datatable.Rows.Add(row2);

            cbbDVT.DataSource = datatable;
            cbbDVT.DisplayMember = "View";
            cbbDVT.ValueMember = "Value";
        }

        #endregion

        #region Hàm lấy tên đơn vị thời gian

        public static string GetNameDvTG(string sMaDvTG)
        {
            switch (sMaDvTG)
            {
                case Constant.DonViTinhTG.MaDVTGiay:
                    return Constant.DonViTinhTG.TenDVTGiay;
                case Constant.DonViTinhTG.MaDVTPhut:
                    return Constant.DonViTinhTG.TenDVTPhut;
                case Constant.DonViTinhTG.MaDVTGio:
                    return Constant.DonViTinhTG.TenDVTGio;
                case Constant.DonViTinhTG.MaDVTNgay:
                    return Constant.DonViTinhTG.TenDVTNgay;
                case Constant.DonViTinhTG.MaDVTThang:
                    return Constant.DonViTinhTG.TenDVTThang;
                case Constant.DonViTinhTG.MaDVTNam:
                    return Constant.DonViTinhTG.TenDVTNam;
            }
            return null;
        }

        #endregion

        #region Hàm Chuyển đơn vị tính về đơn vị gốc

        //Số lượng chuyển đổi = số lượng gốc * tỉ lệ chuyển đổi
        public static int TinhSoLuongTheoDvtGoc(int iSoLuongHienTai, int iTiLe)
        {
            var iSoLuongGocReturn = iSoLuongHienTai / iTiLe;

            return iSoLuongGocReturn;
        }

        #endregion

        #region Hàm tính tiền dịch vụ tiền giờ

        public static int TinhTienDvTienGio(DateTime dtThoiGianBd, string sIdDvt, long dcSoLuong, int iGiaDoanhThu,
            DateTime dtNow, TimeSpan tsThoiGianTamDung)
        {
            var tsThoiGianSd = dtNow.Subtract(dtThoiGianBd).Subtract(tsThoiGianTamDung);

            decimal tiLe = 0;
            if (sIdDvt == Constant.DonViTinhTG.MaDVTGio)
            {
                var tsDonViTinh = TimeSpan.FromHours((int)dcSoLuong);
                tiLe = (int)(tsThoiGianSd.TotalHours / tsDonViTinh.Hours);
                if (tiLe < 1)
                {
                    tiLe = 1;
                }
            }
            else if (sIdDvt == Constant.DonViTinhTG.MaDVTPhut)
            {
                var tsDonViTinh = TimeSpan.FromMinutes((int)dcSoLuong);
                tiLe = (int)(tsThoiGianSd.TotalMinutes / tsDonViTinh.Minutes);
                if (tiLe < 1)
                {
                    tiLe = 1;
                }
            }
            else if (sIdDvt == Constant.DonViTinhTG.MaDVTGiay)
            {
                var tsDonViTinh = TimeSpan.FromSeconds((int)dcSoLuong);
                tiLe = (int)(tsThoiGianSd.TotalSeconds / tsDonViTinh.Seconds);
                if (tiLe < 1)
                {
                    tiLe = 1;
                }
            }
            else if (sIdDvt == Constant.DonViTinhTG.MaDVTNgay)
            {
                var tsDonViTinh = TimeSpan.FromDays((int)dcSoLuong);
                tiLe = (int)(tsThoiGianSd.TotalDays / tsDonViTinh.TotalDays);
                if (tiLe < 1)
                {
                    tiLe = 1;
                }
            }
            /*else if (iIdDvt == Constant.DonViTinhTG.MaDVTThang)
            {
                TimeSpan tsDonViTinh = TimeSpan.FromDays(iSoLuong);
                tiLe = tsThoiGianSd.TotalSeconds / tsDonViTinh.Seconds;
                if (tiLe < 1)
                {
                    tiLe = 1;
                }
            }
            else if (iIdDvt == Constant.DonViTinhTG.MaDVTNam)
            {
                TimeSpan tsDonViTinh = TimeSpan.FromSeconds(iSoLuong);
                tiLe = tsThoiGianSd.TotalSeconds / tsDonViTinh.Seconds;
                if (tiLe < 1)
                {
                    tiLe = 1;
                }
            }*/
            var iTienGio = (int)(tiLe * iGiaDoanhThu * dcSoLuong);
            return iTienGio;
        }

        #endregion

        #region ham ghep ten

        public static string GhepFullName(decimal dclangguage, string fname, string mname, string lname)
        {
            string fullname;

            if (dclangguage == 1)
                if (String.IsNullOrEmpty(lname))
                    fullname = fname;
                else
                    fullname = fname + " " + mname + " " + lname;
            else if (String.IsNullOrEmpty(lname))
                fullname = fname;
            else
                fullname = lname + " " + mname + " " + fname;
            return fullname;
        }

        #endregion

        #region Hàm GenCode

        public static String GenCode(Object sIdItem, Object sHospitalId)
        {
            return sHospitalId + "." + sIdItem;
        }

        #endregion
    }

    /// <summary>
    ///     Class Implement Enum DateTime
    /// </summary>
    /// <CreatedBy>CuongNQ</CreatedBy>
    /// <Created>24/07/2010</Created>
    public enum DateInterval
    {
        Year,
        Month,
        Weekday,
        Day,
        Hour,
        Minute,
        Second
    }
}